package com.org.mshopping.dao;

import java.util.ArrayList;
import java.util.List;

import com.org.mshopping.model.Category;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseService {
	Context m_context;
	DatabaseHelper m_dbHelper;
	SQLiteDatabase m_db;
	
	static final String DATABASE_NAME = "mShopping.db"; 
	static final int DATABASE_VERSION = 1;
	private static final String TABLE_NAME = "Categories";
	static final String DATABASE_CREATE = "CREATE TABLE " + TABLE_NAME +
			" (_id INTEGER PRIMARY KEY AUTOINCREMENT," +
			" name TEXT, desc TEXT, image INTEGER)";
	
	public DatabaseService(Context c) {
		this.m_context = c;
	}
	
	private class DatabaseHelper extends SQLiteOpenHelper {

		public DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE);
//			Category add = new Category();
//			insertItem(add);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			
		}
	}
	
	public DatabaseService open() throws SQLException {
		m_dbHelper = new DatabaseHelper(m_context);
		m_db = m_dbHelper.getWritableDatabase();
		return this;
	}
	
	public void insertItems(List<Category> categories){
		for(Category c : categories){
			insertItem(c);
		}
	}
	
	public void insertItem(Category c){
		ContentValues values = new ContentValues();
		values.put("name", c.getName());
		values.put("desc", c.getDesc());
		values.put("image", c.getImage());
		
		m_db.insert(TABLE_NAME, null, values);
	}
	
	public Cursor loadItems(){
		return m_db.query(TABLE_NAME, new String[]{"_id","name","desc","image"}, null, null, null, null, null);
	}
	
	public void close() {
		m_dbHelper.close();
	}
}
